package com.chuji.crmcj.act;

import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.ContentObserver;
import android.database.Cursor;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.android.volley.Response;
import com.chuji.crmcj.R;
import com.chuji.crmcj.adapter.MagLineAdapter;
import com.chuji.crmcj.adapter.NoUserAdapter;
import com.chuji.crmcj.adapter.TimeLineAdapter;
import com.chuji.crmcj.bean.ClientDetailInfo;
import com.chuji.crmcj.bean.CusdeleteInfo;
import com.chuji.crmcj.bean.FollDataInfo;
import com.chuji.crmcj.bean.InsRecInfo;
import com.chuji.crmcj.bean.LoanRecInfo;
import com.chuji.crmcj.bean.SalerInfo;
import com.chuji.crmcj.bean.TryDriveInfo;
import com.chuji.crmcj.service.RecordService;
import com.chuji.crmcj.utils.CommonUtil;
import com.chuji.crmcj.utils.ConstantValue;
import com.chuji.crmcj.utils.NumberUtils;
import com.chuji.crmcj.utils.SPUtils;
import com.chuji.crmcj.utils.UIUtils;
import com.chuji.crmcj.utils.UploadUtil;
import com.chuji.crmcj.utils.UrlUtils;
import com.chuji.crmcj.view.CalendarView;
import com.chuji.crmcj.view.CalendarViewDialog;

import org.json.JSONObject;

import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 客户详情  Todo 保险数据不够
 * Todo  添加跟进 参数  reqAddFollow
 * Todo  录音地址问题
 * Todo  customerID = "2D5640C9-EB6B-4A2B-9147-581B3D059A86";
 * Created by w.pitt on 2016/1/13.
 */
public class ClientDetailAct extends BaseActivity implements View.OnClickListener {
    private ListView mLvTimeLine;
    private ImageView mBtAddItem;
    private int screenW;
    private View indicateLine;
    private Button mBtCliDetail;
    private Button mBtCliFollow;
    private RelativeLayout mRlCarInfo;
    private RelativeLayout mRlFolInfo;
    private View viewLine;
    private LinearLayout mBtAppleDef;
    private LinearLayout mBtDeal;
    private LinearLayout mTv_call;
    private LinearLayout mTv_send_message;
    private LinearLayout mTv_client_follow;
    private LinearLayout mTv_change_level;
    private ScrollView mSvScroll;
    private TextView mTvOldData;
    private LinearLayout mLlFunction;
    private RelativeLayout mLlAddFollow;
    private TimeLineAdapter timeLineAdapter;
    private Intent service;
    private ContentResolver resolver;
    private Uri uri;
    private TextView mTvNumber;
    private TextView mTvName;
    private RelativeLayout mRl_client_info;
    private TextView mTv_updata_time;
    private TextView mTv_car_purpose;
    private TextView mCarBudget;
    private TextView mCarMode;
    private TextView mCarUser;
    private TextView mCarSeries;
    private TextView mCarModel;
    private TextView mCarConfiguration;
    private TextView mCarColor;
    private TextView mCompetingModels;
    private TextView mReason;
    private TextView mTv_client_info;
    private View mLine;
    private LinearLayout mLl_item;
    private TextView mTv_work_place;
    private TextView mTv_home_address;
    private TextView mTv_car_mode;
    private TextView mTv_family;
    private TextView mProfession;
    private TextView mTv_hobbies;
    private View mBelow_line;
    private TextView mTv_old_data;
    private TextView mPredictBuyTime;
    private TextView mTvStateDes;
    //    private String salerId;
    private String newContent;
    private AlertDialog addFolDialog;
    private AlertDialog defeatDialog;
    private EditText mEdRemark;
    private String remark;
    private AlertDialog timeDialog;
    //    private String flowID;
    private RelativeLayout mRlTestCar;
    private FollDataInfo follDataInfo;
    private TextView mTv_loan;
    private TextView mTv_loan_date;
    private RelativeLayout mRl_loan;
    private TextView mTv_loan_money;
    private TextView mTv_loan_interest;
    private TextView mTv_loan_year_limt;
    private TextView mTv_car_cost;
    private TextView mTv_totle_cost;
    private TextView mTv_repay_month;
    private TextView mTv_insurance_date;
    //潜客条状进来按钮
    private LinearLayout mLlExpectCusBtn;
    //保有客户进来按钮
    private LinearLayout mLlTenCusBtn;
    private ImageView mIvLevel;
    private TextView mTvDealName;
    private TextView mTvFol;
    private ImageView mLoanIcon;
    private ImageView mInsureIcon;
    private ImageView mComeDoor;
    private ImageView mTextCar;
    private RelativeLayout mRlInsure;
    private String callAim;
    private EditText mEtNewContent;
    private String cusTel;
    private ListView mLvDefRea;
    private LinearLayout mll_tenure_function;
    private LinearLayout mtv_tenure_call;
    private LinearLayout mtv_send_tenure_message;
    private boolean isCompelete;
    private NoUserAdapter adapter;
    private AlertDialog changeLvDig;
    private TextView mTv_cus_type;
    private String customerID;
    private TextView mtv_sale_name;
    private RelativeLayout mrl_sale_info;
    private TextView mtv_sale_time;
    private LinearLayout mLlTrans;
    private LinearLayout mll_trans_cus;
    private LinearLayout mll_delete_cus;
    private ListView mLvTransCus;
    private LinearLayout mtv_mag_change_level;
    private LinearLayout mll_mag_fol;
    private int roleType;
    private LinearLayout mll_mag_function;
    private TextView mtv_calculate_record;
    private ImageView mIvCalTime;
    private WindowManager windowManager;
    CalendarViewDialog dialog;
    private TextView mtv_choice_time;
    private WindowManager.LayoutParams attributes;
    private TextView mtv_want_car;
    private String carModel;
    private TextView mTv_last_time;
    private String createTime;
    private TextView mTv_test_perfor;
    private TextView mTv_test_carmodel;
    private TextView mTvAdditionalCost;
    private String appointmentTime;
    private String currentLevel;
    private TextView mTv_test_peizhi;
    private TextView mTv_buy_type;
    private TextView mhomeinfo;
    private TextView mtv_test_peizhi;
    private String userID;
    private SalerInfo salerInfo;
    public View ll_left;
    private String salerName;
    private View kongbai;
    private CusdeleteInfo cusdeleteInfo;
    private List<FollDataInfo.ApiParamObjEntity> mFollItem;
    private String backCall;
    private String record;
    private MagLineAdapter magLineAdapter;
    private TextView is_mag_fol;

    @Override
    protected void initView() {
        setContentView(R.layout.act_client_detail);
        loading = (FrameLayout) findViewById(R.id.fl_loading);
        mTv_buy_type = (TextView) findViewById(R.id.tv_buy_type);
        mhomeinfo = (TextView) findViewById(R.id.homeinfo);
        mTv_test_carmodel = (TextView) findViewById(R.id.tv_test_carmodel);
        mTv_test_perfor = (TextView) findViewById(R.id.tv_text_perfor);
        mll_tenure_function = (LinearLayout) findViewById(R.id.ll_tenure_function);
        mtv_tenure_call = (LinearLayout) findViewById(R.id.tv_tenure_call);
        mtv_send_tenure_message = (LinearLayout) findViewById(R.id.tv_send_tenure_message);
        mTv_cus_type = (TextView) findViewById(R.id.tv_cus_type);
        mTv_test_peizhi = (TextView) findViewById(R.id.tv_test_peizhi);
        is_mag_fol = (TextView) findViewById(R.id.is_mag_fol);

        mTvAdditionalCost = (TextView) findViewById(R.id.tv_additional_cost);
        mtv_calculate_record = (TextView) findViewById(R.id.tv_calculate_record);
        mll_mag_fol = (LinearLayout) findViewById(R.id.ll_mag_fol);
        mll_mag_function = (LinearLayout) findViewById(R.id.ll_mag_function);

        mtv_sale_name = (TextView) findViewById(R.id.tv_sale_name);
        mrl_sale_info = (RelativeLayout) findViewById(R.id.rl_sale_info);
        mtv_sale_time = (TextView) findViewById(R.id.tv_sale_time);

        mLlTrans = (LinearLayout) findViewById(R.id.ll_mag_option);
        mll_trans_cus = (LinearLayout) findViewById(R.id.ll_trans_cus);
        mll_delete_cus = (LinearLayout) findViewById(R.id.ll_delete_cus);

        mtv_mag_change_level = (LinearLayout) findViewById(R.id.tv_mag_change_level);
        mLoanIcon = (ImageView) findViewById(R.id.loan);
        mRlInsure = (RelativeLayout) findViewById(R.id.rl_insure);
        mInsureIcon = (ImageView) findViewById(R.id.insure);
        mComeDoor = (ImageView) findViewById(R.id.comedoor);
        mTextCar = (ImageView) findViewById(R.id.test_car);
        mRl_loan = (RelativeLayout) findViewById(R.id.rl_loan);
        mTvFol = (TextView) findViewById(R.id.is_fol);
        mIvLevel = (ImageView) findViewById(R.id.iv_level);
        mTvDealName = (TextView) findViewById(R.id.tv_deal_name);
        mLlTenCusBtn = (LinearLayout) findViewById(R.id.tenure_cus_btn);
        mLlExpectCusBtn = (LinearLayout) findViewById(R.id.expect_cus_btn);
        mTv_car_cost = (TextView) findViewById(R.id.tv_car_cost);
        mTv_insurance_date = (TextView) findViewById(R.id.tv_insurance_date);
        mLlFunction = (LinearLayout) findViewById(R.id.ll_function);
        mSvScroll = (ScrollView) findViewById(R.id.sv_scroll);
        mBtAddItem = (ImageView) findViewById(R.id.bt_add_follow);
        mLvTimeLine = (ListView) findViewById(R.id.lv_follow_timeline);
        indicateLine = findViewById(R.id.indicate_line);
        mBtCliDetail = (Button) findViewById(R.id.btn_client_data);
        mBtCliFollow = (Button) findViewById(R.id.btn_client_fol);
        mRlCarInfo = (RelativeLayout) findViewById(R.id.rl_client_info);
        mRlFolInfo = (RelativeLayout) findViewById(R.id.rl_follow_info);
        mBtAppleDef = (LinearLayout) findViewById(R.id.ll_application_defeat);
        mBtDeal = (LinearLayout) findViewById(R.id.ll_deal);
        mRlTestCar = (RelativeLayout) findViewById(R.id.rl_test_car);
        mTv_call = (LinearLayout) findViewById(R.id.tv_call);
        mTv_send_message = (LinearLayout) findViewById(R.id.tv_send_message);
        mTv_client_follow = (LinearLayout) findViewById(R.id.tv_client_follow);
        mTv_change_level = (LinearLayout) findViewById(R.id.tv_change_level);
        mTvOldData = (TextView) findViewById(R.id.tv_old_data);
        mLlAddFollow = (RelativeLayout) findViewById(R.id.rl_add_follow);
        mTvNumber = (TextView) findViewById(R.id.tv_number);
        mTvName = (TextView) findViewById(R.id.tv_name);
        mtv_want_car = (TextView) findViewById(R.id.tv_want_car);
        kongbai = findViewById(R.id.kongbai);

        mTv_loan = (TextView) findViewById(R.id.tv_loan);
        mTv_loan_date = (TextView) findViewById(R.id.tv_loan_date);
        mTv_loan_money = (TextView) findViewById(R.id.tv_loan_money);
        mTv_loan_interest = (TextView) findViewById(R.id.tv_loan_lixi);
        mTv_loan_year_limt = (TextView) findViewById(R.id.tv_loan_year_limt);
        mTv_totle_cost = (TextView) findViewById(R.id.tv_totle_cost);
        mTv_repay_month = (TextView) findViewById(R.id.tv_repay_month);
        mTv_last_time = (TextView) findViewById(R.id.tv_last_time);

        mRl_client_info = (RelativeLayout) findViewById(R.id.rl_client_info);
        mTv_updata_time = (TextView) findViewById(R.id.tv_updata_time);
        mTv_car_purpose = (TextView) findViewById(R.id.tv_car_purpose);
        mCarBudget = (TextView) findViewById(R.id.CarBudget);
        mCarUser = (TextView) findViewById(R.id.CarUser);
        mCarSeries = (TextView) findViewById(R.id.CarSeries);
        mCarModel = (TextView) findViewById(R.id.CarModel);
        mCarConfiguration = (TextView) findViewById(R.id.CarConfiguration);
        mCarColor = (TextView) findViewById(R.id.CarColor);
        mCompetingModels = (TextView) findViewById(R.id.CompetingModels);
        mReason = (TextView) findViewById(R.id.Reason);
        mTv_client_info = (TextView) findViewById(R.id.tv_client_info);
        mLl_item = (LinearLayout) findViewById(R.id.ll_item);
        mTv_work_place = (TextView) findViewById(R.id.tv_work_place);
        mTv_home_address = (TextView) findViewById(R.id.tv_home_address);
        mTv_family = (TextView) findViewById(R.id.tv_family);
        mProfession = (TextView) findViewById(R.id.Profession);
        mTv_hobbies = (TextView) findViewById(R.id.tv_hobbies);
        mBelow_line = (View) findViewById(R.id.below_line);
        mPredictBuyTime = (TextView) findViewById(R.id.tv_expect_buy_time);
        mTvStateDes = (TextView) findViewById(R.id.tv_state_des);
        mtv_test_peizhi = (TextView) findViewById(R.id.tv_test_peizhi);
        ll_left = findViewById(R.id.ll_left);

        //拿到发送信息
        getSmsContent();

        //设置通话音量
        AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        am.adjustStreamVolume(AudioManager.STREAM_VOICE_CALL, AudioManager.ADJUST_RAISE, 0);
    }

    @Override
    protected void initData() {
        mTvBarTitle.setText("客户详情");
        userID = SPUtils.getString(UIUtils.getContext(), "UserID", "");

        Intent intent = getIntent();
        customerID = intent.getStringExtra("CustomerID");
        carModel = intent.getStringExtra("CarModel");
        createTime = intent.getStringExtra("CreateTime");
//        flowID = intent.getStringExtra("FlowID");
        salerName = intent.getStringExtra("SalerName");

        mtv_want_car.setText(carModel);
        mTv_last_time.setText(createTime);

        reqNetData();

        mtv_sale_name.setText(String.valueOf("销售:" + salerName));

        roleType = SPUtils.getInt(UIUtils.getContext(), "RoleType", -1);

        if (roleType != 1) {
            //非销售的
            mLlFunction.setVisibility(View.GONE);
            mLlTrans.setVisibility(View.VISIBLE);
            mll_mag_function.setVisibility(View.VISIBLE);
            mLlExpectCusBtn.setVisibility(View.GONE);
            mrl_sale_info.setVisibility(View.VISIBLE);
        }
        // 初始化指示器宽度
        screenW = getWindowManager().getDefaultDisplay().getWidth();
        indicateLine.getLayoutParams().width = screenW / 2;
        indicateLine.requestLayout(); // 重新计算大小，并刷新控件
    }

    private void reqNetData() {
         /*获取销售员列表*/
        if (roleType != 1) {
            reqSalerList();
        }
        /*顾客信息*/
        reqClientInfo();
        /*贷款信息*/
        reqLoanData();
        /*保险信息*/
        reqInsuareData();
        /*试驾记录*/
        reqTestCar();
    }

    private void reqSalerList() {
        String strURL = String.format(UrlUtils.CustomerInfoChangePeter + "&UserID=%s&CustomerID=%s", userID, customerID);
        volleyRequest(strURL, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                salerInfo = JSON.parseObject(s, SalerInfo.class);
                UIUtils.runInMainThread(new Runnable() {
                    @Override
                    public void run() {
                        if (salerInfo.getApiParamObj().size() != 0) {
                            salerList = true;
                        }
                        loading.setVisibility(View.GONE);
                    }
                });
            }
        });
    }

    private void reqTestCar() {
        String strURL = String.format(UrlUtils.TRY_DRIVE_SHOW + "&CustomerID=%s", customerID);
        volleyRequest(strURL, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                final TryDriveInfo tryDriveInfo = JSON.parseObject(s, TryDriveInfo.class);
                UIUtils.runInMainThread(new Runnable() {
                    @Override
                    public void run() {
                        if (tryDriveInfo.getApiParamObj().size() != 0) {
                            mRlTestCar.setVisibility(View.VISIBLE);
                            mTv_test_carmodel.setText(tryDriveInfo.getApiParamObj().get(0).getCarModel());
                            mTv_test_perfor.setText(tryDriveInfo.getApiParamObj().get(0).getComment());
                            mtv_test_peizhi.setText(tryDriveInfo.getApiParamObj().get(0).getCarConfiguration());
                        } else {
                            mRlTestCar.setVisibility(View.GONE);
                        }
                        loading.setVisibility(View.GONE);
                    }
                });
            }
        });
    }

    private void reqInsuareData() {
        String strURL = String.format(UrlUtils.GETINSRECORDCUSTOMER + "&CustomerID=%s", customerID);
        volleyRequest(strURL, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                final InsRecInfo insRecInfo = JSON.parseObject(s, InsRecInfo.class);
                UIUtils.runInMainThread(new Runnable() {
                    @Override
                    public void run() {
                        if (insRecInfo.getCount() == 0) {
                            mRlInsure.setVisibility(View.GONE);
                        } else {
                            mtv_calculate_record.setVisibility(View.VISIBLE);
                            mTv_car_cost.setText(insRecInfo.getApiParamObj().get(0).getCarAmount());
                            mTv_insurance_date.setText(insRecInfo.getApiParamObj().get(0).getCreateTime());
                            //TODO 数据不够
                        }
                    }
                });
            }
        });
    }

    private void reqLoanData() {
        String strURL = String.format(UrlUtils.GETLOANRECINFOBYCUS + "&CustomerID=%s", customerID);
        volleyRequest(strURL, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                final LoanRecInfo loanRecInfo = JSON.parseObject(s, LoanRecInfo.class);
                UIUtils.runInMainThread(new Runnable() {
                    @Override
                    public void run() {
                        if (loanRecInfo.getCount() == 0) {
                            mRl_loan.setVisibility(View.GONE);
                        } else {
                            mtv_calculate_record.setVisibility(View.VISIBLE);
                            mLoanIcon.setImageDrawable(UIUtils.getDrawable(R.drawable.loanb));
                            mTv_loan_money.setText(String.valueOf(loanRecInfo.getApiParamObj().get(0).getAmount()));
                            mTv_loan_interest.setText(loanRecInfo.getApiParamObj().get(0).getRate());
                            mTv_loan_year_limt.setText(loanRecInfo.getApiParamObj().get(0).getYears());
                            mTv_totle_cost.setText(String.valueOf(loanRecInfo.getApiParamObj().get(0).getTotalAmount()));
                            mTv_repay_month.setText(loanRecInfo.getApiParamObj().get(0).getMonthAmount());
                            mTv_loan_date.setText(loanRecInfo.getApiParamObj().get(0).getCreateTime());
                            mTvAdditionalCost.setText(String.valueOf(loanRecInfo.getApiParamObj().get(0).getTotalAmount() - loanRecInfo.getApiParamObj().get(0).getAmount()));
                        }
                    }
                });
            }
        });
    }

    private int lable = 0;

    //  把跟进分为销售员和经理端
    private void reqFollData() {
        String strURL = UrlUtils.GETRECORDDETAILLSIT + "&CustomerID=" + customerID;
        volleyRequest(strURL, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                follDataInfo = JSON.parseObject(s, FollDataInfo.class);
                UIUtils.runInMainThread(new Runnable() {
                    @Override
                    public void run() {
                        if (roleType == 1) {
                            if (timeLineAdapter == null) {
                                mFollItem = follDataInfo.getApiParamObj();
                                timeLineAdapter = new TimeLineAdapter(ClientDetailAct.this, mFollItem, lable);
                                mLvTimeLine.setAdapter(timeLineAdapter);
                            } else {
                                timeLineAdapter.notifyDataSetChanged();
                            }
                        } else {
                            if (magLineAdapter == null) {
                                mFollItem = follDataInfo.getApiParamObj();
                                magLineAdapter = new MagLineAdapter(ClientDetailAct.this, mFollItem, lable);
                                mLvTimeLine.setAdapter(magLineAdapter);
                            } else {
                                magLineAdapter.notifyDataSetChanged();
                            }
                        }
                    }
                });
            }
        });
    }


    @Override
    protected void onStart() {
        super.onStart();
    }

    private void reqClientInfo() {
        String strURL = String.format(UrlUtils.GETCLIENTInfo + "&CustomerID=%s", customerID);
        volleyRequest(strURL, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                final ClientDetailInfo clientDetailInfo = JSON.parseObject(s, ClientDetailInfo.class);
                UIUtils.runInMainThread(new Runnable() {
                    @Override
                    public void run() {
                        if (clientDetailInfo.getApiParamObj().size() != 0) {
                            cusTel = clientDetailInfo.getApiParamObj().get(0).getTel();

                            String tel = clientDetailInfo.getApiParamObj().get(0).getTel();
                            if (tel.length() == 11) {
                                mTvNumber.setText(NumberUtils.parsePhoneNumber(tel));
                            } else {
                                mTvNumber.setText(tel);
                            }

                            mTvName.setText(clientDetailInfo.getApiParamObj().get(0).getName());
//                            mtv_want_car.setText(clientDetailInfo.getApiParamObj().get(0).get);
                            mTv_work_place.setText(clientDetailInfo.getApiParamObj().get(0).getWorkPlace());
                            mTv_home_address.setText(clientDetailInfo.getApiParamObj().get(0).getHomeAddress());
                            mProfession.setText(clientDetailInfo.getApiParamObj().get(0).getProfession());
                            mTv_hobbies.setText(clientDetailInfo.getApiParamObj().get(0).getHobbies());
                            mTv_updata_time.setText(clientDetailInfo.getApiParamObj().get(0).getUpdateTime());
                            if (clientDetailInfo.getApiParamObj().get(0).isIsImportance()) {
                                mTvFol.setText("取消重点");
                            }
                            mTv_buy_type.setText(clientDetailInfo.getApiParamObj().get(0).getCarMode());
                            mhomeinfo.setText(clientDetailInfo.getApiParamObj().get(0).getHomeInfo());
                            mTv_car_purpose.setText(clientDetailInfo.getApiParamObj().get(0).getCarPurpose());
                            mCarBudget.setText(clientDetailInfo.getApiParamObj().get(0).getCarBudget() + "");
//                            mTv_car_mode.setText(clientDetailInfo.getApiParamObj().get(0).getCarMode());
                            mCarUser.setText(clientDetailInfo.getApiParamObj().get(0).getCarUser());
                            mCarSeries.setText(clientDetailInfo.getApiParamObj().get(0).getCarSeries());
                            mCarModel.setText(clientDetailInfo.getApiParamObj().get(0).getCarModel());
                            mCarConfiguration.setText(clientDetailInfo.getApiParamObj().get(0).getCarConfiguration());
                            mCarColor.setText(clientDetailInfo.getApiParamObj().get(0).getCarColor());
                            mCompetingModels.setText(clientDetailInfo.getApiParamObj().get(0).getCompetingModels());
                            mReason.setText(clientDetailInfo.getApiParamObj().get(0).getReason());
                            mPredictBuyTime.setText(clientDetailInfo.getApiParamObj().get(0).getPredictBuyTime());
                            mTvStateDes.setText(clientDetailInfo.getApiParamObj().get(0).getComment());
                            mTv_cus_type.setText(clientDetailInfo.getApiParamObj().get(0).getCustomerType());
                            customerLevel = clientDetailInfo.getApiParamObj().get(0).getCustomerLevel();
                            if (customerLevel == "O") {
                                mTvDealName.setText("确认成交");
                            }
                            mIvLevel.setImageDrawable(CommonUtil.getLevelIcon(customerLevel));
                            isCompelete = clientDetailInfo.getApiParamObj().get(0).isIsCompelete();

                            if (isCompelete) {
                                lable = 1;
                                //Todo 保有客户
                                if (roleType == 1) {
//                                mTv_client_follow.setVisibility(View.GONE);
//                                mTv_change_level.setVisibility(View.GONE);
                                    mLlAddFollow.setVisibility(View.GONE);
                                    mBtDeal.setVisibility(View.GONE);
                                    mBtAppleDef.setVisibility(View.GONE);
                                    mLlTenCusBtn.setVisibility(View.VISIBLE);
                                    mLlExpectCusBtn.setVisibility(View.GONE);
                                    mIvLevel.setVisibility(View.GONE);
                                    mll_tenure_function.setVisibility(View.VISIBLE);
                                    mLlFunction.setVisibility(View.GONE);
                                } else {
                                    // 经理端 的保有客户
                                    mll_mag_function.setVisibility(View.GONE);
                                    mIvLevel.setVisibility(View.GONE);
                                    kongbai.setVisibility(View.GONE);
                                    mTv_last_time.setText("成交车型");
                                }
                            }

                            if (clientDetailInfo.getApiParamObj().get(0).getIsShow() != 0) {
                                //Todo 有试驾
                                mRlTestCar.setVisibility(View.VISIBLE);
                                mTextCar.setImageDrawable(UIUtils.getDrawable(R.drawable.carb));
                            }
                            /*跟进记录*/
                            reqFollData();
                        }
                    }
                });
            }
        });
    }

    private void getSmsContent() {
        // 1.1 得到内容提供者的解析器
        resolver = this.getContentResolver();
        // 1.2 指定短信内容提供者的uri
        uri = Uri.parse("content://sms/");
        // 1.3 调用解析器查询的方法
        // 3.注册观察者
        // uri 内容提供者的uri , 就是要给这个提供者注册一个观察者
        // notifyForDescendents 以content://sms/开的uri中的数据发生变化时是否通知观察者
        resolver.registerContentObserver(uri, true, new MyObserver(new Handler()));
    }

    private class MyObserver extends ContentObserver {

        public MyObserver(Handler handler) {
            super(handler);
        }

        /**
         * 观察者接收到提供者的通知时调用这个方法
         * 提供者中的数据发生变化时调用这个方法
         * type 1表示接收到的短信,  2表示发送的短信,
         */
        @Override
        public void onChange(boolean selfChange) {
            super.onChange(selfChange);
            // 通过内容提供者查询数据库
            Cursor cursor = resolver.query(uri, new String[]{"address", "date", "type", "body"}, null, null, "date desc");
            if (cursor != null && cursor.getCount() > 0 && isFirst) {
                isFirst = false;
//            if (cursor != null) {
                cursor.moveToNext();
                String address = cursor.getString(0);
                int type = cursor.getInt(2);
                if (type == 2 && address.equals(cusTel)) {
                    String body = cursor.getString(3);
                    System.out.println("----------address=" + address + ";  type= " + type + ";  body==" + body);
                    smsBody = body;
                    //添加短信
                    reqAddFollow("2", "短信", "", smsBody, String.valueOf("0"));
                }
            }
            cursor.close();
        }
    }

    private boolean isFirst = true;
    private String smsBody = "";

    @Override
    protected void initListener() {
        mll_delete_cus.setOnClickListener(this);
        ll_left.setOnClickListener(this);
        mBtAddItem.setOnClickListener(this);
        mBtCliDetail.setOnClickListener(this);
        mBtCliFollow.setOnClickListener(this);
        mBtAppleDef.setOnClickListener(this);
        mBtDeal.setOnClickListener(this);
        mTv_call.setOnClickListener(this);
        mTv_send_message.setOnClickListener(this);
        mTv_client_follow.setOnClickListener(this);
        mTv_change_level.setOnClickListener(this);
        mTvOldData.setOnClickListener(this);
        mLlTenCusBtn.setOnClickListener(this);
        mtv_tenure_call.setOnClickListener(this);
        mtv_send_tenure_message.setOnClickListener(this);
        mtv_mag_change_level.setOnClickListener(this);
        mll_mag_fol.setOnClickListener(this);

        mll_trans_cus.setOnClickListener(this);
    }

    private void showFollowDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        final AlertDialog dialog = builder.create();
        View view = View.inflate(this, R.layout.layout_follow_level, null);// 给dialog设定特定布局
        // dialog.setView(view);
        dialog.setView(view, 0, 0, 0, 0);// 去掉上下左右边距, 兼容2.x版本
        Button mBtSave = (Button) view.findViewById(R.id.btn_sure);
        Button mBtCancel = (Button) view.findViewById(R.id.btn_cancel);
        final TextView mTvFolType = (TextView) view.findViewById(R.id.tv_isfollow);

        if (roleType == 1) {
            if (mTvFol.getText() == "取消重点") {
                mTvFolType.setText("取消重点客户跟进？");
            }
            mBtSave.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (mTvFol.getText() == "取消重点") {
                        mTvFol.setText("重点跟进");
                        //取消重点跟进
                        reqIsStrenFoll(0);
                    } else {
                        mTvFol.setText("取消重点");
                        // 设置重点跟进
                        reqIsStrenFoll(1);
                    }
                    dialog.dismiss();
                }
            });
        } else {

            if (is_mag_fol.getText() == "取消重点") {
                mTvFolType.setText("取消重点客户跟进？");
            }
            mBtSave.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (is_mag_fol.getText() == "取消重点") {
                        is_mag_fol.setText("重点跟进");
                        //取消重点跟进
                        reqIsStrenFoll(0);
                    } else {
                        is_mag_fol.setText("取消重点");
                        // 设置重点跟进
                        reqIsStrenFoll(1);
                    }
                    dialog.dismiss();
                }
            });
        }
        mBtCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        dialog.show();
    }

    private void reqIsStrenFoll(int IsImportance) {
//        String strURL = String.format(UrlUtils.REQISSTRENFOLLOW + "&IsImportance=%d&CustomerID=%s&SalesID=%s", IsImportance, customerId, salerId);
//        volleyRequest(strURL, new Response.Listener<String>() {
//            @Override
//            public void onResponse(String s) {
//                UIUtils.runInMainThread(new Runnable() {
//                    @Override
//                    public void run() {
//                        UIUtils.showToastSafe("设置跟进成功！");
//                    }
//                });
//            }
//        });
        String strURL = String.format(UrlUtils.REQISSTRENFOLLOW);

        Map<String, String> map = new HashMap<String, String>();
        map.put("IsImportance", String.valueOf(IsImportance));
        map.put("CustomerID", customerID);
        postRequest(strURL, map, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                UIUtils.showToastSafe("设置跟进成功！");
            }
        });
    }

    //    private String selectLevel;
    private void showLevelDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        changeLvDig = builder.create();
        View view = View.inflate(this, R.layout.layout_change_level, null);  //给dialog设定特定布局
        ListView mLvChangeLv = (ListView) view.findViewById(R.id.lv_change_level);
        NoUserAdapter noUserAdapter = new NoUserAdapter(5);
        mLvChangeLv.setAdapter(noUserAdapter);
//        NiceSpinner mNpChangelevel = (NiceSpinner) view.findViewById(R.id.np_change_level);
//        final ArrayList<String> arrayList = new ArrayList<String>(Arrays.asList("N", "H", "A", "B", "C"));
//        mNpChangelevel.attachDataSource(arrayList);
//        mNpChangelevel.setSelectedIndex(0);
//        mNpChangelevel.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
//            @Override
//            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
//                selectLevel = arrayList.get(i);
//            }
//
//            @Override
//            public void onNothingSelected(AdapterView<?> adapterView) {
//
//            }
//        });
        // dialog.setView(view);

        changeLvDig.setView(view, 0, 0, 0, 0); // 去掉上下左右边距, 兼容2.x版本
        Button mBtSave = (Button) view.findViewById(R.id.btn_sure);
        Button mBtCancel = (Button) view.findViewById(R.id.btn_cancel);
        mBtSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                currentLevel = SPUtils.getString(UIUtils.getContext(), "currentLevel", "");
                if (TextUtils.isEmpty(currentLevel)) {
                    UIUtils.showToastSafe("请选择修改级别");
                } else {
                    reqChangeLev();
                    changeLvDig.dismiss();
                }
            }
        });

        mBtCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                changeLvDig.dismiss();
                SPUtils.saveString(UIUtils.getContext(), "currentLevel", "");
            }
        });
        changeLvDig.show();
    }

    private void reqChangeLev() {
//        String strURL = String.format(UrlUtils.CHANGELEVEL + "&OldCustomerLevel=%s&CustomerLevel=%s&CustomerID=%s&FlowID=%s&SalesID=%s", "1", "1", customerId, flowID, salerId);
//        volleyRequest(strURL, new Response.Listener<String>() {
//            @Override
//            public void onResponse(String s) {
//                UIUtils.runInMainThread(new Runnable() {
//                    @Override
//                    public void run() {
//                        UIUtils.showToastSafe("修改成功！");
//                    }
//                });
//            }
//        });
        String strURL = String.format(UrlUtils.CHANGELEVEL);
        Map<String, String> map = new HashMap<String, String>();
        map.put("OldCustomerLevel", customerLevel);
        map.put("CustomerLevel", currentLevel);
        map.put("CustomerID", customerID);
//        map.put("FlowID", flowID);
        map.put("SalesID", userID);
        postRequest(strURL, map, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                UIUtils.showToastSafe("修改等级提交成功");
                mIvLevel.setImageDrawable(CommonUtil.getLevelIcon(currentLevel));
                    /*跟进记录*/
                reqFollData();
//                FollDataInfo.ApiParamObjEntity newInfo = new FollDataInfo.ApiParamObjEntity();
//                newInfo.setAttachment("");
//                newInfo.setTaskDetail("修改等级为" + customerLevel);
//                newInfo.setTaskTypeContent("修改等级");
//
//                mFollItem = timeLineAdapter.getList();
//                mFollItem.add(0, newInfo);
//                if (roleType == 1) {
//                    timeLineAdapter.notifyDataSetChanged();
//                } else {
//                    magLineAdapter.notifyDataSetChanged();
//                }
            }
        });
    }

    private String customerLevel;

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_left:
                finish();
                break;
            case R.id.bt_add_follow:
                addFolDialog();
                break;
            case R.id.btn_client_data:
                mSvScroll.smoothScrollTo(0, 0);
                lineTranslation(screenW / 2, 0);
                mBtCliFollow.setTextColor(UIUtils.getColor(R.color.font3));
                mBtCliDetail.setTextColor(UIUtils.getColor(R.color.qianlan));
                mRlCarInfo.setVisibility(View.VISIBLE);
                mRlFolInfo.setVisibility(View.GONE);
                break;
            case R.id.btn_client_fol:
                mSvScroll.smoothScrollTo(0, 0);
                lineTranslation(0, screenW / 2);
                mBtCliFollow.setTextColor(UIUtils.getColor(R.color.qianlan));
                mBtCliDetail.setTextColor(UIUtils.getColor(R.color.font3));
                mRlCarInfo.setVisibility(View.GONE);
                mRlFolInfo.setVisibility(View.VISIBLE);
                break;
            case R.id.ll_application_defeat:
                /*申请战败*/
                showApplyDef();
                break;
            case R.id.ll_deal:
                if (customerLevel == "O") {
                    // level == "O"  订单客户  确认成交
                    reDealDialog();
                } else {
                    Intent intent = new Intent(this, NewtaskActivity.class);
                    //Todo  非订单客户点击成交按钮 弹出 成交或者订单按钮
                    intent.putExtra("SOURCE", ConstantValue.REDEAL);
                    intent.putExtra("CustomerID", customerID);
                    startActivity(intent);
                    overridePendingTransition(R.anim.act_in, 0);
                }
                break;
            case R.id.ll_trans_cus:
                //客户转移
                showTransDig();
                break;
            case R.id.ll_delete_cus:
                //客户删除
                showDeleteDlg();
                break;
            case R.id.ll_mag_fol:
                showFollowDialog();
                break;

            case R.id.tv_call:
                showCallDialog();
                break;
            case R.id.tv_tenure_call:
                showCallDialog();
                break;
            case R.id.tv_send_message:
                isFirst = true;
                sendMessage();
                break;
            case R.id.tv_send_tenure_message:
                isFirst = true;
                sendMessage();
                break;
            case R.id.tv_client_follow:
                showFollowDialog();
                break;
            case R.id.tv_change_level:
                if (customerLevel == "O" || customerLevel == "o") {
                    UIUtils.showToastSafe("订单客户不能修改等级");
                } else {
                    showLevelDialog();
                }
                break;
            case R.id.tv_mag_change_level:
                if (customerLevel == "O" || customerLevel == "o") {
                    UIUtils.showToastSafe("订单客户不能修改等级");
                } else {
                    showLevelDialog();
                }
                break;
            case R.id.tv_old_data:
                Intent intent = new Intent(this, BeforeDataAct.class);
                intent.putExtra("CustomerID", customerID);
                startActivity(intent);
                break;
            case R.id.tenure_cus_btn:
                /*再次成交*/
                Intent reDealInt = new Intent(this, NewtaskActivity.class);
                reDealInt.putExtra("CustomerID", customerID);
                reDealInt.putExtra("SOURCE", ConstantValue.REDEAL);
                startActivity(reDealInt);
                overridePendingTransition(R.anim.act_in, 0);
                break;
        }
    }

    private void reDealDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        final AlertDialog dealDialog = builder.create();
        View view = View.inflate(this, R.layout.dialog_order_deal, null);// 给dialog设定特定布局
        // dialog.setView(view);
        dealDialog.setView(view, 0, 0, 0, 0);// 去掉上下左右边距, 兼容2.x版本
        Button mBtSave = (Button) view.findViewById(R.id.btn_sure);
        Button mBtCancel = (Button) view.findViewById(R.id.btn_cancel);
        final TextView mTvFolType = (TextView) view.findViewById(R.id.tv_isfollow);
        mBtSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                reqOrderDeal();
                dealDialog.dismiss();
            }
        });
        mBtCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dealDialog.dismiss();
            }
        });
        dealDialog.show();
    }

    private void reqOrderDeal() {
//        String strURL = String.format(UrlUtils.SUREORDERDEAL +
//                "&SalesID=%s&CustomerID=%s&FlowID=%s", salerId, customerID, flowID);
//        volleyRequest(strURL, new Response.Listener<String>() {
//            @Override
//            public void onResponse(String s) {
//                UIUtils.runInMainThread(new Runnable() {
//                    @Override
//                    public void run() {
//                        UIUtils.showToastSafe("订单确认成功！");
//                    }
//                });
//            }
//        });

        String strURL = String.format(UrlUtils.SUREORDERDEAL);
        Map<String, String> map = new HashMap<String, String>();
        map.put("SalesID", userID);
        map.put("CustomerID", customerID);
//        map.put("FlowID", flowID);
        postRequest(strURL, map, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                UIUtils.showToastSafe("成交已确认");
            }
        });
    }

    private boolean salerList = false;

    private void showTransDig() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        final AlertDialog dialog = builder.create();
        View view = View.inflate(this, R.layout.dialog_costome_trans, null);// 给dialog设定特定布局
        // dialog.setView(view);
        dialog.setView(view, 0, 0, 0, 0);// 去掉上下左右边距, 兼容2.x版本

        mLvTransCus = (ListView) view.findViewById(R.id.lv_trans_cus);
        Button mBtSave = (Button) view.findViewById(R.id.btn_sure);
        Button mBtCancel = (Button) view.findViewById(R.id.btn_cancel);
        if (salerList) {
            //销售员列表显示
            adapter = new NoUserAdapter(6, salerInfo);
            mLvTransCus.setAdapter(adapter);

            mBtSave.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    reqTransCus();
                    dialog.dismiss();
                }
            });

            mBtCancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialog.dismiss();
                }
            });
            dialog.show();

        } else {
            UIUtils.showToastSafe("销售员列表为空，请检查网络");
        }
    }

    private void reqTransCus() {
        String strURL = String.format(UrlUtils.CustomerInfoTransferPeter + "&UserID=%s&CustomerID=%s", userID, customerID);
        volleyRequest(strURL, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                final CusdeleteInfo transCusInfo = JSON.parseObject(s, CusdeleteInfo.class);
                UIUtils.runInMainThread(new Runnable() {
                    @Override
                    public void run() {
                        if (transCusInfo.getApiParamObj().get(0).getIsok() == 1) {
                            UIUtils.showToastSafe("客户已转移");
                        }
                    }
                });
            }
        });
    }

    private void showDeleteDlg() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        final AlertDialog dialog = builder.create();
        View view = View.inflate(this, R.layout.dialog_delete, null);// 给dialog设定特定布局
        // dialog.setView(view);
        dialog.setView(view, 0, 0, 0, 0);// 去掉上下左右边距, 兼容2.x版本
        Button mBtSave = (Button) view.findViewById(R.id.btn_sure);
        Button mBtCancel = (Button) view.findViewById(R.id.btn_cancel);

        mBtSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                reqDeleteCus();
                dialog.dismiss();
            }
        });

        mBtCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        dialog.show();
    }

    private void reqDeleteCus() {

        String strURL = String.format(UrlUtils.CustomerInfoDelPeter + "&UserID=%s&CustomerID=%s", userID, customerID);
        volleyRequest(strURL, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                cusdeleteInfo = JSON.parseObject(s, CusdeleteInfo.class);
                UIUtils.runInMainThread(new Runnable() {
                    @Override
                    public void run() {
                        if (cusdeleteInfo.getApiParamObj().get(0).getIsok() == 1) {
                            UIUtils.showToastSafe("客户已删除");
                            finish();
                        }
                    }
                });
            }
        });
    }

    private void sendMessage() {
        Uri smsToUri = Uri.parse("smsto:" + "18362379823");
        Intent intent = new Intent(Intent.ACTION_SENDTO, smsToUri);
        intent.putExtra("sms_body", "");
        startActivity(intent);
//        service = new Intent(this, MesService.class);
//        startService(service);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        timeLineAdapter = null;
        magLineAdapter = null;
        if (service != null) {
            stopService(service);
        }
    }

    private void showCallDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        final AlertDialog dialog = builder.create();
        View view = View.inflate(this, R.layout.dialog_call, null);// 给dialog  设定特定布局
        ListView mLvCallItem = (ListView) view.findViewById(R.id.lv_call_item);
        TextView mTvCallNul = (TextView) view.findViewById(R.id.tv_call_num);
        mTvCallNul.setText("拨打号码：" + cusTel);
        if (isCompelete) {
            adapter = new NoUserAdapter(4);
        } else {
            adapter = new NoUserAdapter(2);
        }
        mLvCallItem.setAdapter(adapter);

        // dialog.setView(view);
        dialog.setView(view, 0, 0, 0, 0);// 去掉上下左右边距, 兼容2.x版本
        Button mBtSave = (Button) view.findViewById(R.id.btn_sure);
        Button mBtCancel = (Button) view.findViewById(R.id.btn_cancel);
//        RadioGroup mRgCall = (RadioGroup) view.findViewById(R.id.call_radio);
//        mRgCall.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
//            @Override
//            public void onCheckedChanged(RadioGroup radioGroup, int checkedId) {
//                switch (checkedId) {
//                    case R.id.rb_return_call:
//                        isLable = 0;
//                        break;
//                    case R.id.rb_invitation_door:
//                        isLable = 1;
//                        break;
//                    case R.id.rb_invitation_car:
//                        isLable = 1;
//                        break;
//                    case R.id.rb_invitation_action:
//                        isLable = 1;
//                        break;
//                    case R.id.rb_other:
//                        isLable = 0;
//                        break;
//                }
//            }
//        });

        mBtSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isCompelete) {
                    callAim = SPUtils.getString(UIUtils.getContext(), "backCall", "");
                } else {
                    callAim = SPUtils.getString(UIUtils.getContext(), "callAim", "");
                }
                if (TextUtils.isEmpty(callAim)) {
                    UIUtils.showToastSafe("请选择");
                } else {
                    //进行录音
                    service = new Intent(ClientDetailAct.this, RecordService.class);
                    startService(service);

                    dialog.dismiss();
                    //进行拨号
//                    Intent phoneIntent = new Intent( "android.intent.action.CALL", Uri.parse("tel:" + cusTel));
                    Intent phoneIntent = new Intent("android.intent.action.CALL", Uri.parse("tel:" + "18362379823"));

//                phoneIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    // 启动
                    startActivity(phoneIntent);
                }
            }
        });
        mBtCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                SPUtils.saveString(UIUtils.getContext(), "callAim", "");
                SPUtils.saveString(UIUtils.getContext(), "backCall", "");
            }
        });
        dialog.show();
    }

    /*电话 结束后  邀约弹窗*/
    @Override
    protected void onResume() {
        super.onResume();
        new RecordService().showDialog(new RecordService.CallBackInterface() {
            @Override
            public void callBackFunction() {
                record = SPUtils.getString(UIUtils.getContext(), "Record", "");
                /**
                 * 当记录为空时，时长 ==0 时 。
                 * 不添加网络
                 * 不发送到网络。
                 * 电话没成功。不产生跟进记录
                 */
                if (!TextUtils.isEmpty(record) && !record.equals("")) {
                    //获取录音长度
                    int recordLength = getRecordLength(record);
                    if (!TextUtils.isEmpty(String.valueOf(recordLength)) && recordLength != 0) {
                        //不管要不邀约 只要是电话  都上传
                        uploadLY();
                        int isShowCal = SPUtils.getInt(UIUtils.getContext(), "isShowCal", -1);
                        if (isShowCal == 1) {
                            CallFinDialog();
                        } else {
                            reqAddFollow("1", "电话跟进", callAim, record, String.valueOf(recordLength));
                        }
                    }
                }
            }

            private int getRecordLength(String path) {
                MediaPlayer mp = MediaPlayer.create(ClientDetailAct.this, Uri.parse(path));
                int duration = mp.getDuration();
                return duration / 1000;
            }
        });
    }

    private void uploadLY() {
        new Thread(new Runnable() {
            @Override
            public void run() {

                File file = new File(record);
                String strUrl = "";//UrlUtils.updateluyin;
                UploadUtil.uploadFile(file, strUrl);
            }
        }).start();
    }

//    @Override
//    protected void onStart() {
//        super.onStart();
//        new RecordService().showDialog(new RecordService.CallBackInterface() {
//            @Override
//            public void callBackFunction() {
//                if (isLable == 1) {
//                    UIUtils.showToastSafe("123");
//                    CallFinDialog();
//                }
//            }
//        });
//    }

    private void CallFinDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        timeDialog = builder.create();
        View view = View.inflate(this, R.layout.dialog_sure_time, null);// 给dialog设定特定布局
        // dialog.setView(view);
        timeDialog.setView(view, 0, 0, 0, 0);// 去掉上下左右边距, 兼容2.x版本
        mtv_choice_time = (TextView) view.findViewById(R.id.tv_choice_time);
        mIvCalTime = (ImageView) view.findViewById(R.id.iv_invitation);
        mIvCalTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mIvCalTime.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        dialog = new CalendarViewDialog(ClientDetailAct.this);
                        dialog.show();
                        dialog.calendar.setOnItemClickListener(new CalendarView.OnItemClickListener() {
                            @Override
                            public void OnItemClick(Date selectedStartDate, Date selectedEndDate, Date downDate) {
                                if (dialog.calendar.isSelectMore()) {
                                    UIUtils.showToastSafe(dialog.format.format(selectedStartDate) + "到" + dialog.format.format(selectedEndDate));
                                } else {
                                    appointmentTime = dialog.format.format(downDate);
                                    mtv_choice_time.setText(dialog.format.format(downDate));
                                    dialog.dismiss();
                                }
                            }
                        });
                        windowManager = getWindowManager();
                        attributes = dialog.getWindow().getAttributes();
                        //p.height = (int) (d.getHeight() * 0.3);   //高度设置为屏幕的0.3
                        attributes.width = windowManager.getDefaultDisplay().getWidth();//为获取屏幕宽、高,宽度设置为全屏
                        dialog.getWindow().setAttributes(attributes);     //设置生效
                    }
                });
            }
        });
        Button mBtSave = (Button) view.findViewById(R.id.btn_sure);
        Button mBtCancel = (Button) view.findViewById(R.id.btn_cancel);
        mBtSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                reqSureForPhone();
                timeDialog.dismiss();
            }
        });
        mBtCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                timeDialog.dismiss();
            }
        });
        timeDialog.show();
    }

    private void reqSureForPhone() {
//        String strURL = String.format(UrlUtils.INSERTOFFERBYPHONE + "&SalesID=%s&OfferType=%s&BackTime=%s&CustomerID=%s&CustomerLevel=%s&Comment=%s&Attachment=%s", salerId, callAim,appointmentTime, customerID, customerLevel, "备注", "录音地址");
//        volleyRequest(strURL, new Response.Listener<String>() {
//            @Override
//            public void onResponse(String s) {
//                UIUtils.runInMainThread(new Runnable() {
//                    @Override
//                    public void run() {
//                        UIUtils.showToastSafe("邀约成功！");
//                    }
//                });
//            }
//        });

        //这块添加的是邀约的
        String strURL = String.format(UrlUtils.INSERTOFFERBYPHONE);
        Map<String, String> map = new HashMap<String, String>();
        map.put("SalesID", userID);
        map.put("OfferType", callAim);
        map.put("BackTime", appointmentTime);
        map.put("CustomerID", customerID);
        map.put("CustomerLevel", customerLevel);
        map.put("Comment", "备注");
        map.put("Attachment", record);
        postRequest(strURL, map, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                UIUtils.showToastSafe("邀约成功");
                //添加到记录
            }
        });
    }

    private String aprDefeatReason;

    private void showApplyDef() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        defeatDialog = builder.create();
        View view = View.inflate(this, R.layout.layout_apply_def, null);// 给dialog设定特定布局
        // dialog.setView(view);
        defeatDialog.setView(view, 0, 0, 0, 0);// 去掉上下左右边距, 兼容2.x版本
        mEdRemark = (EditText) view.findViewById(R.id.et_def_remark);
        mLvDefRea = (ListView) view.findViewById(R.id.lv_def_reason);
        adapter = new NoUserAdapter(1);
        mLvDefRea.setAdapter(adapter);
//        NiceSpinner mNsDefReason = (NiceSpinner) view.findViewById(R.id.def_reason);
//        final ArrayList<String> arrayList = new ArrayList<String>(Arrays.asList("放弃购车", "选购竞品", "同城购车"));
//        mNsDefReason.attachDataSource(arrayList);
//        mNsDefReason.setSelectedIndex(0);
//        mNsDefReason.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
//            @Override
//            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
//                aprDefeatReason = arrayList.get(i);
//            }
//
//            @Override
//            public void onNothingSelected(AdapterView<?> adapterView) {
//
//            }
//        });
        Button mBtSave = (Button) view.findViewById(R.id.btn_sure);
        Button mBtCancel = (Button) view.findViewById(R.id.btn_cancel);
        mBtSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                remark = mEdRemark.getText().toString().trim();
                aprDefeatReason = SPUtils.getString(UIUtils.getContext(), "defReason", "");
                if (TextUtils.isEmpty(aprDefeatReason)) {
                    UIUtils.showToastSafe("请选择申请失败理由");
                } else if (TextUtils.isEmpty(remark)) {
                    UIUtils.showToastSafe("请输入战败原因详情");
                } else {
                    reqDefeatApprove();
                    defeatDialog.dismiss();
                }
            }
        });
        mBtCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                defeatDialog.dismiss();
                SPUtils.saveString(UIUtils.getContext(), "defReason", "");
            }
        });
        defeatDialog.show();
    }

    private void reqDefeatApprove() {
//        String strURL = String.format(UrlUtils.DEFAPRFORCUSTOME +
//                "CustomerID=%s&SalesID=%s&DefeatReason=%s&Comment=%s", customerId, salerId, aprDefeatReason, remark);
//        volleyRequest(strURL, new Response.Listener<String>() {
//            @Override
//            public void onResponse(String s) {
//                UIUtils.runInMainThread(new Runnable() {
//                    @Override
//                    public void run() {
//                        UIUtils.showToastSafe("修改成功！");
//                    }
//                });
//            }
//        });
        String strURL = String.format(UrlUtils.DEFAPRFORCUSTOME);
        Map<String, String> map = new HashMap<String, String>();
        map.put("CustomerID", customerID);
        map.put("SalesID", userID);
        map.put("DefeatReason", aprDefeatReason);
        map.put("Comment", remark);
        postRequest(strURL, map, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                UIUtils.showToastSafe("战败申请已提交");
            }
        });
    }

    private String selectFolType;

    private void addFolDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        addFolDialog = builder.create();
        View view = View.inflate(this, R.layout.layout_add_follow, null);// 给dialog设定特定布局
        ListView mLvAddNewFol = (ListView) view.findViewById(R.id.lv_add_new_fol);
        NoUserAdapter adapter = new NoUserAdapter(3);
        mLvAddNewFol.setAdapter(adapter);
        // dialog.setView(view);
//        NiceSpinner mAddNewFollow = (NiceSpinner) view.findViewById(R.id.add_new_follow);
//        final ArrayList<String> arrayList = new ArrayList<String>(Arrays.asList("微信", "QQ", "上门", "其他"));
//        mAddNewFollow.attachDataSource(arrayList);
//        mAddNewFollow.setSelectedIndex(0);
//        mAddNewFollow.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
//            @Override
//            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
//                selectFolType = arrayList.get(i);
//            }
//            @Override
//            public void onNothingSelected(AdapterView<?> adapterView) {
//            }
//        });
        addFolDialog.setView(view, 0, 0, 0, 0);// 去掉上下左右边距, 兼容2.x版本
        Button mBtSave = (Button) view.findViewById(R.id.btn_save);
        Button mBtCancel = (Button) view.findViewById(R.id.btn_cancel);
        mEtNewContent = (EditText) view.findViewById(R.id.et_new_content);
        mBtSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                newContent = mEtNewContent.getText().toString().trim();
                selectFolType = SPUtils.getString(UIUtils.getContext(), "newFol", "");
                if (TextUtils.isEmpty(newContent)) {
                    UIUtils.showToastSafe("请输入跟进详情");
                } else if (TextUtils.isEmpty(selectFolType)) {
                    UIUtils.showToastSafe("请选择跟进方式");
                } else {
                    reqAddFollow("3", selectFolType, newContent, "", "");
                    addFolDialog.dismiss();
                }
            }
        });
        mBtCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                addFolDialog.dismiss();
                SPUtils.saveString(UIUtils.getContext(), "newFol", "");
            }
        });
        addFolDialog.show();
    }

    private void reqAddFollow(final String taskType, final String mTaskTypeContent, final String mTaskDetail, final String mAttachment, final String mSoundTime) {
//        String strURL = String.format(UrlUtils.ADDFOLLOWDATA +
//                "&FlowID=%s&CustomerID=%s&TaskType=%d&TaskTypeContent=%s&TaskDetail=%s&Attachment=%s&SalesID=%s", flowID, customerId, 0, selectFolType, newContent, mEtNewContent, "录音地址或短信内容", salerId);
//        volleyRequest(strURL, new Response.Listener<String>() {
//            @Override
//            public void onResponse(String s) {
//                UIUtils.runInMainThread(new Runnable() {
//                    @Override
//                    public void run() {
//                        UIUtils.showToastSafe("设置跟进成功！");
//                        //Todo
//                        addFolDialog.dismiss();
//                        FollDataInfo.ApiParamObjEntity newInfo = new FollDataInfo.ApiParamObjEntity();
//                        newInfo.setAttachment("");
//                        newInfo.setTaskDetail(newContent);
//                        newInfo.setTaskTypeContent(selectFolType);
//                        follDataInfo.getApiParamObj().add(0, newInfo);
//                        timeLineAdapter.notifyDataSetChanged();
//                    }
//                });
//            }
//        });
        String strURL = UrlUtils.ADDFOLLOWDATA;
        Map<String, String> map = new HashMap<String, String>();
//        map.put("FlowID", flowID);
        map.put("CustomerID", customerID);
        map.put("TaskType", taskType);  //1电话 2短信 3其他
        map.put("TaskTypeContent", mTaskTypeContent); //方式具体内容 (QQ，电话，微信等)
        map.put("TaskDetail", mTaskDetail);  //跟进详情
        map.put("Attachment", mAttachment); //录音地址或短信内容
        map.put("SoundTime", mSoundTime);
        postRequest(strURL, map, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                UIUtils.showToastSafe("设置跟进成功！");
                /*添加到集合中
                * 实时更新
                * todo setAttachment
                * */


                   /*跟进记录*/
                reqFollData();

//                FollDataInfo.ApiParamObjEntity newInfo = new FollDataInfo.ApiParamObjEntity();
//                newInfo.setAttachment(mAttachment);
//                newInfo.setTaskDetail(mTaskDetail);
//                newInfo.setTaskTypeContent(mTaskTypeContent);
//
//
//                if (timeLineAdapter == null) {
//                    mFollItem.add(newInfo);
//                    timeLineAdapter = new TimeLineAdapter(ClientDetailAct.this, mFollItem, lable);
//                    mLvTimeLine.setAdapter(timeLineAdapter);
//                } else {
//                    mFollItem = timeLineAdapter.getList();
//                    mFollItem.add(0, newInfo);
//                    timeLineAdapter.notifyDataSetChanged();
//                }
//
//                if (magLineAdapter == null) {
//                    mFollItem.add(newInfo);
//                    magLineAdapter = new MagLineAdapter(ClientDetailAct.this, mFollItem, lable);
//                    mLvTimeLine.setAdapter(magLineAdapter);
//                } else {
//                    mFollItem = magLineAdapter.getList();
//                    mFollItem.add(0, newInfo);
//                    magLineAdapter.notifyDataSetChanged();
//                }

                if (taskType.equals("2")) {
                    //短信跳转
                    //跳转至该Fragment 显示
                    mSvScroll.smoothScrollTo(0, 0);
                    lineTranslation(0, screenW / 2);
                    mBtCliFollow.setTextColor(UIUtils.getColor(R.color.qianlan));
                    mBtCliDetail.setTextColor(UIUtils.getColor(R.color.font3));
                    mRlCarInfo.setVisibility(View.GONE);
                    mRlFolInfo.setVisibility(View.VISIBLE);
                }
            }
        });
    }

    public void lineTranslation(int startX, int finishX) {
        float y = indicateLine.getY();
        TranslateAnimation ta = new TranslateAnimation(startX, finishX, 0, 0);
        ta.setDuration(200);
        ta.setFillAfter(true);
        indicateLine.setAnimation(ta);
    }
}
